﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using ETWebApi2.Models;
using Model;
using BllFactory;
using IBLL;

namespace ETWebApi2.Controllers
{
    
    [Route("chart"), JwtAuthActionFilter]
    public class MyChartController : ApiController
    {
        private IVIEW_PRService m_prService= ServiceFactory.CreatService<IVIEW_PRService>();
        private ICUser_tbService m_userServer = ServiceFactory.CreatService<ICUser_tbService>();
        /// <summary>
        /// legent
        /// </summary>
        /// <param name="QueryType">1上传 0下载(统计已下载的文件)</param>
        [HttpGet]
        public HttpResponseMessage GetChart(int QueryType,int times)
        {
            JwtAuthObject info = new BaseClass().GetInfoByToken(Request.Headers.Authorization.Parameter);
            CUser_tb currentUser = m_userServer.GetList(u => u.Id == info.UserId).FirstOrDefault();
            //获取所有合作伙伴  
            List<VIEW_PR> partners = m_prService.GetList(p=>p.SelfCompanyId==currentUser.CompanyId && p.State!=2).OrderByDescending(p=>p.filenum).ToList();
            DateTime now = DateTime.Now.AddYears(-1);
            int count = 12;
            switch (times)
            {
                case 1: now = DateTime.Now.AddYears(-1); count = 12; break;
                case 3: now = DateTime.Now.AddMonths(-3); count = times; break;
                case 6: now = DateTime.Now.AddMonths(-6); count = times; break;
                case 9: now = DateTime.Now.AddMonths(-9); count = times; break;
                default: 
                    break;
            }
            List<EChart.series> sList = new List<EChart.series>();
            if (QueryType == 1)
            {
                sList = GetEchartData5("Time", string.Format("VIEW_UPLOAD where upload={0}", currentUser.CompanyId), "download", partners, now);
            }
            else
            {
                sList = GetEchartData5("dTime", string.Format("VIEW_DOWNLOAD where download={0}", currentUser.CompanyId), "upload", partners, now);
            }
            HandSeries(times,ref sList,now,count);     
            List<string> names = new List<string>();
            List<Item> items = new List<Item>();
            for (int i = 0; i < sList.Count; i++)
            {
                names.Add(sList[i].name);
                Item it = new Item() {CompanyName=sList[i].name,Data=sList[i].yVal };
                items.Add(it);
            }
            return ObjectToJson.toJson(new { status=200,data=new{total=names.Count,legent=names, series=items }
        });
        }
        
        /// <summary>
        /// 用于处理某个客户上传的统计或者下载的统计
        /// </summary>
        /// <param name="pId">公司ID 不传递此参数 则查找全部</param>
        /// <returns></returns>
        public List<EChart.series> GetEchartData5(string field, string where, string who, List<VIEW_PR> customs,DateTime timeNow) 
        {
            List<EChart.series> sList = new List<EChart.series>();

            //最近一年的数据  
            DateTime year3 = timeNow;
            //把时间变为对应的星期六的时间 
            string time = string.Format("DATEDIFF(month,'{1}', {0})", field,year3);

            string sql = string.Format("select {4} as itemName, count(*) as count, {3} as who from {1} and {0}>'{2}' group by {4}, {3} order by {4}",
                                        field, where, year3, who, time);

            List<ItemList3> lt = new List<ItemList3>();
            List<Item> result = new List<Item>();

            using (var context = new MyETLockContext())
            {
                lt = context.Database.SqlQuery<ItemList3>(sql).ToList();
            }       
            if (lt.Count == 0)
                return sList;
            foreach (VIEW_PR c in customs)
            {
                sList.Add(new EChart.series(c.Name));
            }
            int maxMoth = 0;
            int all = 0;
            for (int i = 0; i < lt.Count; i++)
            {
                ItemList3 il = lt[i];
                int index = customs.FindIndex((VIEW_PR t) => il.who == t.PartnerId);
                if (index != -1)
                {
                    maxMoth = Math.Max(maxMoth, lt[i].itemName);
                    sList[index].Add(maxMoth ==0?timeNow.AddMonths(1).ToShortDateString():timeNow.AddMonths(maxMoth).ToShortDateString(), lt[i].count);
                    all += lt[i].count;
                }
            }
            all = (int)((double)all / customs.Count);

            for (int i = sList.Count - 1; i >= 0; i--)
            {
                if (sList[i].xVal.Count == 0)
                    sList.RemoveAt(i);
            }
            return sList;
        }


        //处理数据
        private void HandSeries(int times, ref List<EChart.series> sList,DateTime now,int count)
        {            
            List<string> time = new List<string>();
            for (int i = 0; i < count; i++)
            {
                time.Add((now.AddMonths(i + 1).ToShortDateString()));
            }
            for (int i = 0; i < sList.Count; i++)
            {
                for (int j = 0; j < time.Count; j++)
                {
                    List<string> x = sList[i].xVal;
                    if (!x.Contains(time[j]))
                    {
                        sList[i].Add(time[j], 0);
                    }
                    else
                    {
                        sList[i].Add(time[j], sList[i].yVal[0]);
                        sList[i].yVal.Remove(sList[i].yVal[0]);
                    }
                }
            }            
        }

        // GET: api/MyChart/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/MyChart
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/MyChart/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/MyChart/5
        public void Delete(int id)
        {
        }
    }
}
